from django.utils import timezone
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import BasicAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.views import ObtainJSONWebToken
from apps.account.my_ldap import MyLdap
from apps.account.models import LoonUser
from apps.account.serializers import FetchAccountUserSerializer
from rest_framework_jwt.serializers import jwt_payload_handler

from rest_framework_jwt.serializers import jwt_encode_handler
from rest_framework_jwt.utils import jwt_response_payload_handler
from settings import config


class ShutongObtainJSONWebToken(ObtainJSONWebToken):

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        username = request.data['username']
        password = request.data['password']
        print(username,password)
        mldap = MyLdap(config.MY_LDAP_SERVER_URI, config.MY_LDAP_BIND_DN, config.MY_LDAP_BIND_PASSWORD,
                       config.MY_LDAP_SEARCH_BASE)
        ldap_login = mldap.ldap_login(username=username, password=password)
        print('ldap bind:',ldap_login)
        # ldap_login = True

        if serializer.is_valid():

            userObj = serializer.object.get('user') or request.user
            userObj.last_login = timezone.datetime.now()
            userObj.save()
        elif ldap_login:
            userObj = LoonUser.objects.filter(username=username).first()
            payload = jwt_payload_handler(userObj)
            token = jwt_encode_handler(payload)
            response_data = jwt_response_payload_handler(token, userObj, request)
            response = Response(response_data)
            return response

        return super(ShutongObtainJSONWebToken, self).post(request, *args, **kwargs)


class AccountUserViewSet(ViewSet):
    authentication_classes = [BasicAuthentication, JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    @action(methods=['get'], detail=False, url_path='fetch-users')
    def fetch(self, request, format='json'):
        queryset = LoonUser.objects.all()
        serializer = FetchAccountUserSerializer(queryset, many=True)
        return Response({'code': 0, 'data': serializer.data, 'msg': ''},
                        status=status.HTTP_200_OK)
